package com.my.kindlesend.service.impl;

import com.my.kindlesend.service.MailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * 邮件服务实现类
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MailServiceImpl implements MailService {

    private final JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    @Override
    public boolean sendMailWithAttachment(String to, String subject, String content, File file) {
        try {
            // 创建MimeMessage对象
            MimeMessage message = javaMailSender.createMimeMessage();
            // 创建MimeMessageHelper对象，设置multipart为true表示支持附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            // 设置邮件信息
            helper.setFrom(username);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            
            // 添加附件
            if (file != null && file.exists()) {
                helper.addAttachment(file.getName(), file);
                log.info("成功添加附件: {}", file.getName());
            } else {
                log.error("附件文件不存在: {}", file != null ? file.getAbsolutePath() : "null");
                return false;
            }
            
            // 发送邮件
            javaMailSender.send(message);
            log.info("邮件发送成功，收件人: {}", to);
            return true;
        } catch (MessagingException e) {
            log.error("邮件发送失败，收件人: {}", to, e);
            return false;
        } catch (Exception e) {
            log.error("邮件发送过程中发生异常，收件人: {}", to, e);
            return false;
        }
    }
}